<template>
    <van-nav-bar
        title="收货地址"
        left-text="返回"
        left-arrow
        @click-left="OnBack"
    />

    <van-address-list
        v-model="ActiveId"
        :list="list"
        default-tag-text="默认"
        @add="OnAdd"
        @edit="OnEdit"
        @select="OnSelect"
    />

</template>

<script setup>
const { proxy } = getCurrentInstance();

const ActiveId = ref(0);
const list = ref([]);
const business = proxy.$business;
const action = ref(proxy.$route.query.action);

onBeforeMount(() =>
{
    GetAddressData();
});

const OnAdd = () => proxy.$router.push('/address/add');
const OnEdit = (item) => proxy.$router.push({path:'/address/edit',query:{addrid:item.id}});

const GetAddressData = async () =>
{
    const params = {
        busid:business.value.id
    }

    const result = await proxy.$http.post('/address/index',params);

    if(result.code === 1)
    {
        let data = [];

        for(let item of result.data)
        {
            data.push({
                id:item.id,
                name:item.consignee,
                tel:item.mobile,
                address:item.region_text + item.address,
                isDefault:item.status == 1 ? true : false
            });

            if(item.status == 1)
            {
                ActiveId.value = item.id
            }
        }

        list.value = data;
    }
}

const OnSelect = async (info,index) =>
{
    if(action.value === 'confirm')
    {
        proxy.$address.value = {
            id:info.id,
            name:info.name,
            tel:info.tel,
            region_text:info.address
        }

        proxy.$router.back();
    }else{
        const params = {
            id:info.id,
            busid:business.value.id
        }
        
        const result = await proxy.$http.post('/address/select',params);

        if(result.code === 1)
        {
            list.value.map((item) => item.isDefault = false);

            list.value[index].isDefault = true;
        }else{
            proxy.$fail(result.msg);
        }
    }
}

const OnBack = () => proxy.$router.back();
</script>